//
//  XGL_PersonalImageDetailViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/21.
//

import UIKit
import MJRefresh
import FSPagerView
import JXPhotoBrowser

class XGL_PersonalImageDetailViewController: XGL_CommentInputViewController,ScrollviewAdjustInset,CustomNavgationBar{
    typealias DeleteHandler = ()->Void
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    lazy var pagerView = FSPagerView()
    lazy var pageControl = FSPageControl()
    lazy var animationView = XGL_GiftAnimationView()
    let header = MJRefreshNormalHeader()
    let footer = MJRefreshBackNormalFooter()
    var userHeader: UserHeadView!
    var userNameText: UILabel!
    var contentText: UILabel!
    var followItem: UIButton!
    var labelView: VideoMarkView!
    var dateText: UILabel!
    var thumbItem: MXCustomButton!
    var commentView: XGL_PersonalCommentView!
    var detailData: PublishData?
    var handler: DeleteHandler?
    
    var page: NSInteger = 1
    var thumbCount: NSInteger = 0{
        didSet{
            if thumbCount > 0 {
                self.thumbItem.setTitle(thumbCount.description, for: .normal)
            }else{
                self.thumbItem.setTitle("0", for: .normal)
            }
            self.thumbItem.imagePosition(at: .left, space: 6.6)
        }
    }
    var banners: [String] = []{
        didSet{
            self.pageControl.numberOfPages = self.banners.count
            self.pagerView.reloadData()
        }
    }

    override func viewDidLoad() {
        self.createCustomBackgroundView()
        super.viewDidLoad()
        adjustInset()
        self.createXglView()
        self.loadData()
        self.creatClearNavigationBar(title: "Details")
        self.getCommentDatasRequest()
        self.getIsFollowRequest()
        self.view.bringSubviewToFront(self.backView)
        self.touchDismissKeyboard = true
    }
    
    func loadData(){
        guard let data = self.detailData else { return }
        if let images = data.data3?.components(separatedBy: ",") {
            self.banners = images
        }
        self.contentText.text = data.data2
        self.labelView.labels = data.data6.components(separatedBy: ",")
        if data.listActionType.contains(2){
            self.thumbItem.isSelected = true
        }else{
            self.thumbItem.isSelected = false
        }
        if let thumbDic = data.listActionCount.first(where: {$0.type == 2}) {
            self.thumbCount = thumbDic.cnt
        }
        if let date = data.createTime.stringToDate() {
            self.dateText.text = date.toFormat("yyyy.MM.dd HH:mm")
        }
        if let userData = data.auditUserExt {
            self.userHeader.userData = userData
            self.userNameText.text = userData.data1
            if userData.userId.description == XGL_userDataManager.share.userId{
                self.followItem.isHidden = true
            }
        }
    }
    
    override func sendComment(commentText: String) {
        guard let data = self.detailData else { return }
        self.commentRequest(id: data.id, content: commentText)
    }
    override func sendGift(giftData: GiftData) {
        self.sendGiftRequest(giftData: giftData)
    }
}

extension XGL_PersonalImageDetailViewController{
    @objc private func followAction(sender: UIButton){
        sender.isSelected = !sender.isSelected
        guard let data = self.detailData, let infor = data.auditUserExt else { return }
        self.followRequest(id: infor.userId.description, asFollow: sender.isSelected)
    }
    
    @objc private func refresh(){
        self.page = 1
        self.getCommentDatasRequest()
    }
    @objc private func getMore(){
        self.getCommentDatasRequest()
    }
    @objc private func moreItemAction(){
        guard let data = self.detailData, let infor = data.auditUserExt else { return }
        let actionController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let action = UIAlertAction(title: "Report", style: .default) { _ in
            let vc = XGL_ReportReasonViewController()
            vc.id = data.id
            self.navigationController?.pushViewController(vc)
        }
        let action1 = UIAlertAction(title: "Block", style: .default) { _ in
            self.alertPicker(message: "Whether to blocklist him ？") { [weak self] in
                guard let `self` = self else { return }
                self.addBlacklistRequest()
            }
        }
        let action3 = UIAlertAction(title: "Delete", style: .default) { _ in
            self.alertPicker(message: "Delete or not ？") { [weak self] in
                guard let `self` = self else { return }
                self.deleteRequest()
            }
        }
        let color = UIColor.hexColor("#FE1A27")
        action3.setValue(color, forKey: "titleTextColor")
        let action2 = UIAlertAction(title: "Cancel", style: .cancel)
        if XGL_userDataManager.share.userId == infor.userId.description{
            actionController.addAction(action3)
        }else{
            actionController.addAction(action)
            actionController.addAction(action1)
        }
        actionController.addAction(action2)
        self.present(actionController, animated: true)
    }
    @objc private func thumbItemAction(sender: UIButton){
        sender.isSelected = !sender.isSelected
        if sender.isSelected{
            self.thumbCount += 1
        }else{
            self.thumbCount -= 1
        }
        if let data = self.detailData {
            self.thumbRequest(id: data.id, isThumb: sender.isSelected)
        }
        
    }
}

extension XGL_PersonalImageDetailViewController{
    private func alertPicker(message: String,handler:@escaping ()->Void){
        let actionController = UIAlertController(title: "Warm reminder", message: message, preferredStyle: .alert)
        let action3 = UIAlertAction(title: "Sure", style: .default) { _ in
            handler()
        }
        let action2 = UIAlertAction(title: "Cancel", style: .cancel)
        actionController.addAction(action2)
        actionController.addAction(action3)
        self.present(actionController, animated: true)
    }
}

extension XGL_PersonalImageDetailViewController{
    private func getCommentDatasRequest(){
        guard let data = self.detailData else { return }
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishCommentData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: nil, page: self.page, size: 20, data1: "3", pid: data.id, data5: nil))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let model = response.resultData{
                    self.commentView.commentCount = model.totalElements
                    if self.header.isRefreshing{
                        self.commentView.datasource = model.data
                        self.header.endRefreshing()
                        self.footer.resetNoMoreData()
                    }else if self.footer.isRefreshing{
                        self.commentView.datasource.append(contentsOf: model.data)
                        self.footer.endRefreshing()
                    }else{
                        self.commentView.datasource = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.footer.endRefreshingWithNoMoreData()
                    }
                    self.commentView.tableView.reloadData()
                }
                break
            default:
                break
            }
        }
    }
    
    private func getIsFollowRequest(){
        guard let data = self.detailData, let infor = data.auditUserExt else { return }
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .IsFollowUser(userId: infor.userId.description))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let followResult = NSInteger(response.resultJson){
                    self.followItem.isSelected = followResult == 1
                }
                break
            default:
                break
            }
        }
    }
    
    func thumbRequest(id: String,isThumb: Bool){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Handler(auditTreeDataId: id, type: 2, actionResult: isThumb))) { result in
            switch result{
            case .success(let response):
                break
            default:
                break
            }
        }
    }
    func commentRequest(id: String,content: String){
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        let data = PublishParamsData(data1: "3",pid: id,data8: content)
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .PublishData(data: data))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                self.header.beginRefreshing()
                break
            default:
                break
            }
        }
    }
    
    func sendGiftRequest(giftData: GiftData){
        guard let data = self.detailData, let infor = data.auditUserExt else { return }
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<SendGiftResult>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .SendGift(giftId: giftData.id, userId: infor.userId.description))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.giftPickerView.coin = data.amount
                    if data.enough == 0{
                        MXProgressHUD.hudWithText("Gift failure")
                    }else if data.enough == 2{
                        MXProgressHUD.hudWithText("Your balance is insufficient, please top it up")
                    }
                    if data.enough > 0{
                        if let data = self.detailData,let infor = data.auditUserExt {
                            self.animationView.showGiftAnimation(message: "\(infor.data1) received a gift from \(XGL_userDataManager.share.userName)", giftData: giftData)
                        }
                    }
                }
                break
            default:
                break
            }
        }
    }
    
    func deleteRequest(){
        guard let data = self.detailData else { return }
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<SendGiftResult>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .DeleteTreeData(id: data.id))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                MXProgressHUD.hudWithText("Successfully deleted") {
                    self.navigationController?.popViewController()
                }
                if let block = self.handler {
                    block()
                }
                break
            default:
                break
            }
        }
    }
    
    func addBlacklistRequest(){
        guard let data = self.detailData,let infor = data.auditUserExt else { return }
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        PanRequestManager<XGL_RequestBaseResponse<SendGiftResult>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .AddBlacklist(userId: infor.userId.description))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                XGL_Notice.default.post(name: XGL_Notification.addBlack.notificationName, object: nil)
                MXProgressHUD.hudWithText("Submit successfully") {
                    self.navigationController?.popViewController()
                }
                if let block = self.handler {
                    block()
                }
                break
            default:
                break
            }
        }
    }
    
    private func followRequest(id: String,asFollow: Bool){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .Follow(userId: id, isFollow: asFollow))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                break
            default:
                break
            }
        }
    }
}

extension XGL_PersonalImageDetailViewController{
    private func browseImage(index: NSInteger){
        
        let images = self.banners
        let browser = JXPhotoBrowser()
        browser.numberOfItems = {
            images.count
        }
        browser.reloadCellAtIndex = { context in
            let imageData = images[context.index]
            let browserCell = context.cell as? JXPhotoBrowserImageCell

            browserCell?.imageView.loadImageWithUrl(imageData)
        }
        browser.pageIndex = 0
        browser.show()
    }
}

extension  XGL_PersonalImageDetailViewController: FSPagerViewDelegate,FSPagerViewDataSource{
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.banners.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
//        let model = imageNames[index]
        cell.contentView.layerCornerRadius = 4.0
        cell.contentView.clipsToBounds = true
        if let url = URL(string:self.banners[index]) {
            cell.imageView?.kf.setImage(with: url)
        }
    
        return cell
    }
  
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        self.pageControl.currentPage = index
        self.browseImage(index: index)
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        guard self.pageControl.currentPage != pagerView.currentIndex else {
            return
        }
        self.pageControl.currentPage = pagerView.currentIndex // Or Use KVO with property "currentIndex"
    }
}


extension XGL_PersonalImageDetailViewController{
    private func createXglView(){

        let scrollView = UIScrollView()
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.showsVerticalScrollIndicator = false
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(inputBar.snp.top)
        }
        let contentView = UIView()
        scrollView.addSubview(contentView)
        contentView.snp.makeConstraints { (make) in
            make.edges.equalTo(scrollView)
            make.width.equalTo(scrollView)
        }
        header.setTitle("Pull down refresh", for: .idle)
        header.setTitle("Release update", for: .pulling)
        header.setTitle("Refresh...", for: .refreshing)
        header.setRefreshingTarget(self, refreshingAction: #selector(self.refresh))
        scrollView.mj_header = header
        footer.setTitle("No more data", for: .noMoreData)
        footer.setRefreshingTarget(self, refreshingAction: #selector(self.getMore))
        scrollView.mj_footer = footer
        self.pagerView.dataSource = self
        self.pagerView.delegate = self
        self.pagerView.automaticSlidingInterval =  3
        self.pagerView.isInfinite = true
        //self.pagerView.interitemSpacing = 50
        self.pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
        contentView.addSubview(self.pagerView)
        self.pagerView.snp.makeConstraints { (make) in
            make.centerX.width.equalToSuperview()
            make.height.equalTo(self.pagerView.snp.width).multipliedBy(299.0/375.0)
            make.top.equalToSuperview()
        }
        
        self.pageControl.numberOfPages = self.banners.count
        self.pageControl.contentHorizontalAlignment = .center
        pageControl.setFillColor(.white, for: .normal)
        pageControl.setFillColor(UIColor.hexColor("#80FFE6"), for: .selected)
        contentView.addSubview(self.pageControl)
        self.pageControl.snp.makeConstraints { (make) in
            make.width.equalTo(50)
            make.height.equalTo(10)
            make.bottom.equalTo(pagerView.snp.bottom).offset(-15)
            make.centerX.equalToSuperview()
        }
        self.userHeader = UserHeadView().then({ make in
            make.layerCornerRadius = 4.0
            make.clipsToBounds = true
        })
        self.userNameText = UILabel().then({ make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 14.0)
        })
        followItem = UIButton().then({ make in
            make.setTitle("Follow", for: .normal)
            make.setTitle("Unfollow", for: .selected)
            make.setTitleColor(UIColor.hexColor("#191A1D"), for: .normal)
            make.titleLabel?.font = UIFont.pingfangSC_Regular(fontSize: 14.0)
            make.backgroundColor = UIColor.hexColor("#80FFE6")
            make.layerCornerRadius = 4.0
            make.addTarget(self, action: #selector(self.followAction(sender:)), for: .touchUpInside)
        })
        self.contentText = UILabel().then({ make in
            make.textColor = .white
            make.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.numberOfLines = 0
            make.lineBreakMode = .byWordWrapping
        })
        self.labelView = VideoMarkView()
        self.dateText = UILabel().then({ make in
            make.textColor = .white
            make.font = UIFont.pingfangSC_Regular(fontSize: 14.0)
        })
        self.thumbItem = MXCustomButton().then({ make in
            make.setImage(imageWithName("icon_thumb_normal"), for: .normal)
            make.setImage(imageWithName("icon_thumb_selected"), for: .selected)
            make.setTitle("0", for: .normal)
            make.setTitleColor(UIColor.white, for: .normal)
            make.titleLabel?.font = UIFont.pingfangSC_Regular(fontSize: 12.0)
            make.imagePosition(at: .left, space: 6.6)
            make.addTarget(self, action: #selector(self.thumbItemAction(sender:)), for: .touchUpInside)
        })
        self.commentView = XGL_PersonalCommentView()
        contentView.addSubviews([userHeader,userNameText,followItem,contentText,labelView,dateText,thumbItem,self.commentView])
        userHeader.snp.makeConstraints { make in
            make.centerY.equalTo(self.pagerView.snp.bottom)
            make.left.equalTo(15.0)
            make.width.height.equalTo(60.0)
        }
        
        userNameText.snp.makeConstraints { make in
            make.left.equalTo(userHeader)
            make.top.equalTo(userHeader.snp.bottom).offset(12.0)
        }
        followItem.snp.makeConstraints { make in
            make.top.equalTo(pagerView.snp.bottom).offset(28.0)
            make.right.equalTo(-15.0)
            make.width.equalTo(conversionWithScrennWidth(value: 60.0))
            make.height.equalTo(26.0)
        }
        contentText.snp.makeConstraints { make in
            make.left.equalTo(userNameText)
            make.top.equalTo(followItem.snp.bottom).offset(16.0)
            make.centerX.equalToSuperview()
        }
        labelView.snp.makeConstraints { make in
            make.left.equalTo(8.0)
            make.top.equalTo(contentText.snp.bottom).offset(8.0)
            make.centerX.equalToSuperview()
        }
        dateText.snp.makeConstraints { make in
            make.left.equalTo(userNameText)
            make.top.equalTo(labelView.snp.bottom).offset(12.0)
        }
        thumbItem.snp.makeConstraints { make in
            make.right.equalTo(-15.0)
            make.centerY.equalTo(dateText)
            make.height.equalTo(24.0)
        }
        commentView.snp.makeConstraints { make in
            make.width.centerX.equalToSuperview()
            make.top.equalTo(dateText.snp.bottom).offset(15.0)
        }
        contentView.snp.makeConstraints { make in
            make.bottom.equalTo(commentView)
        }
        self.view.addSubview(self.animationView)
        self.animationView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.height.equalTo(50.0)
            make.top.equalTo(PanNavibarH + 5.0)
        }
    }
    
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
        let imageIcon = imageWithName("icon_xgl_back_white")
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let backItem = MXCustomButton().then { make in
            make.setImage(imageIcon, for: .normal)
            make.buttonSelectAction { [weak self] in
                guard let `self` = self else { return }
                self.backAction()
            }
        }
        let titleView = UILabel().then { make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.text = title
        }
        let rightItem = UIButton().then { make in
            make.setImage(imageWithName("icon_more_white"), for: .normal)
            make.addTarget(self, action: #selector(self.moreItemAction), for: .touchUpInside)
        }
        navView.addSubview(backItem)
        navView.addSubview(titleView)
        navView.addSubview(rightItem)
        self.view.addSubview(navView)
        backItem.snp.makeConstraints { make in
            make.left.equalTo(5.0)
            make.width.height.equalTo(50.0)
            make.bottom.equalTo(-3.0)
        }
        titleView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backItem)
        }
        rightItem.snp.makeConstraints { make in
            make.centerY.equalTo(backItem)
            make.right.equalTo(-12.0)
            make.width.height.equalTo(26.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
